<template>
  <el-menu
    :default-active="activeMenu"
    mode="horizontal"
    @select="handleSelect"
  >
    <template v-for="(item, index) in topMenus">
      <el-menu-item
        :style="{
          '--theme': theme,
          background: currentSelect === index ? '#f18e1e' : '',
          'border-color': currentSelect === index ? '#f18e1e' : '',
          'border-bottom-color':
            currentSelect === index ? '#f18e1e !important' : '',
        }"
        :index="item.path"
        :key="index"
        @click="selectFn(index, item)"
      >
        <el-tooltip
          class="item"
          effect="dark"
          :content="item.meta.title"
          placement="bottom"
        >
          <svg-icon :icon-class="item.meta.icon" />
        </el-tooltip>
      </el-menu-item>
    </template>

    <!-- 顶部菜单超出数量折叠 -->
    <!-- <el-submenu
      :style="{ '--theme': theme }"
      index="more"
      v-if="topMenus.length > visibleNumber"
    >
      <template v-for="(item, index) in topMenus">
        <el-menu-item
          :index="item.path"
          :key="index"
          v-if="index >= visibleNumber"
        >
       
          {{ item.meta.title }}
        </el-menu-item>
      </template>
    </el-submenu> -->
  </el-menu>
</template>

<script>
import { constantRoutes } from "@/router";
import { bus } from "@/wss/utils/bus.js";

export default {
  data() {
    return {
      currentSelect: 0,
      // 顶部栏初始数
      visibleNumber: 8,
      // 是否为首次加载
      isFrist: false,
      // 当前激活菜单的 index
      currentIndex: undefined,
    };
  },

  computed: {
    theme() {
      return this.$store.state.settings.theme;
    },
    // 顶部显示菜单
    topMenus() {
      let topMenus = [];
      this.routers.map((menu) => {
        // console.log(menu.name.includes('Bm'));
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === "/") {
            topMenus.push(menu.children[0]);
          } else {
            topMenus.push(menu);
          }
        }
      });
      return topMenus;
    },
    // 所有的路由信息
    routers() {
      return this.$store.state.permission.topbarRouters;
    },
    // 设置子路由
    childrenMenus() {
      var childrenMenus = [];
      this.routers.map((router) => {
        for (var item in router.children) {
          if (router.children[item].parentPath === undefined) {
            if (router.path === "/") {
              router.children[item].path =
                "/redirect/" + router.children[item].path;
            } else {
              if (!this.ishttp(router.children[item].path)) {
                router.children[item].path =
                  router.path + "/" + router.children[item].path;
              }
            }
            router.children[item].parentPath = router.path;
          }
          childrenMenus.push(router.children[item]);
        }
      });

      return constantRoutes.concat(childrenMenus);
    },
    // 默认激活的菜单
    activeMenu() {
      const path = this.$route.path;
      // console.log(path, "后台");

      // const arr = []
      // let str = ""
      // str.startsWith()
      // arr.includes
      // 是前台的直接退出
      if (path.startsWith("/Bm-")) return;

      let activePath = this.defaultRouter();
      // 找当前点击的一级菜单的url
      if (path.lastIndexOf("/") > 0) {
        const tmpPath = path.substring(1, path.length);
        activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
      } else if ("/index" == path || "" == path) {
        if (!this.isFrist) {
          this.isFrist = true;
        } else {
          activePath = "index";
        }
      }

      var routes = this.activeRoutes(activePath);
      if (routes.length === 0) {
        activePath = this.currentIndex || this.defaultRouter();
        this.activeRoutes(activePath);
      }
      return activePath;
    },
  },
  beforeMount() {
    window.addEventListener("resize", this.setVisibleNumber);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.setVisibleNumber);
  },
  mounted() {
    //监听前台是否点击了，点击了就干掉后台一级菜单高亮
    this.$bus.$on("changeBackground", () => {
      this.currentSelect = "";
    });
    const path = this.$route.path;
    // 刷新保持高亮 如果当前url再系统下面就让系统保持高亮，系统的索引是0以此类推
    if (path.startsWith("/systems")) {
      this.currentSelect = 0;
    } else if (path.startsWith("/workbench")) {
      this.currentSelect = 1;
    } else if (path.startsWith("/delivery")) {
      this.currentSelect = 2;
    } else if (path.startsWith("/business")) {
      this.currentSelect = 3;
    } else if (path.startsWith("/logAdmin")) {
      this.currentSelect = 4;
    } else if (path.startsWith("/BK")) {
      this.currentSelect = 5;
    } else {
      this.currentSelect = "";
    }
  },
  methods: {
    // 去掉前台的高亮
    selectFn(index, { children }) {
      children[0].meta.isActive = true;
      // 默认跳转第一个二级菜单
      this.$router.push({
        path: children[0].path,
      });
      this.currentSelect = index;

      this.$bus.$emit("AmchangeBackground");
    },
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      const width = document.body.getBoundingClientRect().width / 3;
      this.visibleNumber = parseInt(width / 85);
    },
    // 默认激活的路由
    defaultRouter() {
      let router;

      Object.keys(this.routers).some((key) => {
        if (!this.routers[key].hidden) {
          router = this.routers[key].path;
          return true;
        }
      });
      return router;
    },
    // 菜单选择事件
    handleSelect(key, keyPath) {
      this.currentIndex = key;

      if (this.ishttp(key)) {
        // http(s):// 路径新窗口打开
        window.open(key, "_blank");
      } else if (key.indexOf("/redirect") !== -1) {
        // /redirect 路径内部打开
        this.$router.push({ path: key.replace("/redirect", "") });
      } else {
        // 显示左侧联动菜单
        this.activeRoutes(key);
      }
    },
    // 当前激活的路由 (筛选出三级菜单routes)
    activeRoutes(key) {
      var routes = [];
      if (this.childrenMenus && this.childrenMenus.length > 0) {
        this.childrenMenus.map((item) => {
          if (key == item.parentPath || (key == "index" && "" == item.path)) {
            routes.push(item);
          }
        });
      }
      if (routes.length > 0) {
        routes.find((item) => {
          if (Object.is(item.path, this.$route.path)) item.meta.isActive = true;
        });

        this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
      }
      return routes;
    },
    
    ishttp(url) {
      return url.indexOf("http://") !== -1 || url.indexOf("https://") !== -1;
    },
  },
};
</script>

<style lang="scss" scoped>
// -----------新菜单-----------
ul,li{
  list-style: none;
  margin: 0;
  padding: 0;
}
.top_menu{
  ul{
    display: flex;
    li{
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32px;
      height: 32px;
      border: 1px solid #757f91;
      border-bottom-color: #757f91 !important;
      border-radius: 50%;
      padding: 0 !important;
      margin: 0 10px !important;
      margin-top: 0;
      color: transparent;
      cursor: pointer;
      &:hover{
        background-color: #f18e1e;
        border-color: #f18e1e;
        border-bottom-color: #f18e1e !important;
      }
      .svg-icon {
        font-size: 32px;
      }
    }
  }
}
// -----------新菜单-----------end


.topmenu-container.el-menu--horizontal > .el-menu-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: 1px solid #757f91;
  border-bottom-color: #757f91 !important;
  border-radius: 50%;
  padding: 0 !important;
  margin: 0 10px !important;
  margin-top: 0;
  color: transparent;
}

.topmenu-container.el-menu--horizontal > .el-menu-item:hover,
.topmenu-container.el-menu--horizontal > .el-menu-item.is-active {
  background-color: #f18e1e;
  border-color: #f18e1e;
  border-bottom-color: #f18e1e !important;
}

.topmenu-container.el-menu--horizontal > .el-menu-item .svg-icon {
  font-size: 32px;
  // color: #fff !important;
}

@media (max-width: 1024px) {
  .topmenu-container.el-menu--horizontal > .el-menu-item {
    margin: 0 8px !important;
  }
}
</style>
